//
//  FXOAuthViewController.swift
//  微博(Swift)
//
//  Created by V on 15/12/30.
//  Copyright © 2015年 V. All rights reserved.
//

import UIKit
import SVProgressHUD

// appkey
var WB_APPKEY = "4166654080"
// 回调地址
var WB_REGIRECTURI = "http://www.jobbole.com/"
var WB_SECRET = "189d3ede00765a3954f6ad1ec215d348"

class FXOAuthViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        view = webView
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REGIRECTURI)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
       setupUI()
    }
    
    
    // MARK: - 懒加载 webView
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
    
}




// MARK: - 代理方法  获取 code
// http://www.jobbole.com/?code=e5606df6cd68719c890aa25cc7a94c0a
extension FXOAuthViewController{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL?.absoluteString)
        guard let urlString = request.URL?.absoluteString else{
            return true
        }
        if !urlString.hasPrefix(WB_REGIRECTURI){
            return true
        }
        // 如果代码执行到这里，说明当前 urlString 就是回调页
        // request.URL?.query 是 “http://www.jobbole.com/?code=86656cc9610f58d4b8c55c367a03b03e” 的问号后边的内容
        if let query = request.URL?.query where query.hasPrefix("code="){
            let code = query.substringFromIndex("code=".endIndex)
            // loadAccessToken(code)
            FXUserAccountViewModel.sharedViewModel.loadAccessToken(code, completed: { (isSuccess) -> () in
                if isSuccess {
                    print("请求成功，然后要切换控制器")
                    NSNotificationCenter.defaultCenter().postNotificationName(FXSwitchRootViewControllerNotification, object: self  )
                }else{
                    print("请求失败")
                }
            })
        }else{
            // 用户点击了取消，关闭界面
            clickClose()
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}





// MARK: - 自动填充模块
//document.getElementById('passwd').value
//document.getElementById('userId').value
extension FXOAuthViewController{
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "clickClose")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "clickFill")
        navigationItem.title = "新浪微博"
    }
    
    @objc private func clickClose(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
   
    
    @objc private func clickFill(){
        let jsString = "document.getElementById('userId').value='1010951879@qq.com';document.getElementById('passwd').value='vv01201225.';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

}
